//
//  SXViewController.m
//  尚秀授权
//
//  Created by sunshow-imac on 12-9-24.
//  Copyright (c) 2012年 sunshow-imac. All rights reserved.
//

#import "SXViewController.h"
//#import "ZBarSDK.h"

#import "QRCodeGenerator.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "ZBarSDK.h"
#import "SXQRCodeReader.h"
@interface SXViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,ZBarReaderDelegate,SXQRCodeReaderDelegate>
@property (nonatomic, retain ) SXQRCodeReader *reader;
@end

@implementation SXViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    //[self addShadowAndCornerRadiusWithLayer:self.finalCodeView.layer To:self.view.layer];
    [self addShadowToLayer:self.finalCodeView.layer];


}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
//    return YES;
}

- (void)createImageToPhotoLib:(NSString *)code
{

    if (code.length>0)
    {
        UIImage *image = [QRCodeGenerator qrImageForString:code imageSize:self.view.bounds.size.width];
        [self saveImage:image];
    }

}

- (void)saveImage:(UIImage*)image{
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc]init];
    [assetsLibrary writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error) {
        if (error) {
            NSLog(@"Save image fail：%@",error);
        }else{
            NSLog(@"Save image succeed.");
        }
    }];
}


- (IBAction)showCodeButtonClicked:(id)sender;
{
    [self.finalCodeView setText:@""];
    
    if (self.miniCodeField.text.length >0 &&
        self.padCodeField.text.length  == 12)
    {
        NSString *code = [self getCode:self.miniCodeField.text padCode:self.padCodeField.text];
        
        [self.finalCodeView setText:[NSString stringWithFormat:@"尚秀PAD序列号：\n\n%@",code]];
        [self.finalCodeView setTextColor:[UIColor blackColor]];
        [self.finalCodeView selectAll:self];
        [self createImageToPhotoLib:code];
        
        
        
        
        return;
    }
    
    if (self.miniCodeField.text.length >0 &&
        self.padCodeField.text.length  == 0)
    {
        NSString *code = [self getCode:self.miniCodeField.text padCode:nil];
        
        [self.finalCodeView setText:[NSString stringWithFormat:@"伺服终端序列号：\n\n%@",code]];
        [self.finalCodeView setTextColor:[UIColor blackColor]];
        [self.finalCodeView selectAll:self];
        return;
    }
    
    if (self.miniCodeField.text.length == 0)
    {
        [self.finalCodeView setTextColor:[UIColor redColor]];
        [self.finalCodeView setText:@"主机序列号错误！\n"];
    }
    
    if (self.padCodeField.text.length != 12)
    {
        [self.finalCodeView setTextColor:[UIColor redColor]];
        NSString *tempStr = self.finalCodeView.text;
        [self.finalCodeView setText:[tempStr stringByAppendingString:@"PAD序列号错误！"]];
    }
}

- (NSString *)getCode:(NSString *)miniCode padCode:(NSString *)padCode
{
    NSString *finalCode = nil;
    
    if (miniCode && miniCode.length > 0 )
    {
        finalCode = [[NSString stringWithFormat:@"aisunshow-%@",[miniCode lowercaseString]] stringFromMD5];
        if (padCode && padCode.length>0)
        {
            finalCode = [[NSString stringWithFormat:@"aisunshow-%@%@",[padCode lowercaseString],miniCode] stringFromMD5];
            finalCode = [finalCode substringToIndex:6];
            finalCode = [NSString stringWithFormat:@"%@-%@",finalCode,miniCode];
        }
    }
    
    return finalCode;
}

- (IBAction)finishEdit:(id)sender;
{
    [self.miniCodeField resignFirstResponder];
    [self.padCodeField resignFirstResponder];
}

- (void)addShadowAndCornerRadiusWithLayer:(CALayer *)viewLayer To:(CALayer *)targetLayer
{
    CALayer *shadowlayer =[CALayer layer];
    shadowlayer.frame = viewLayer.frame;
    
    [self addShadowToLayer:shadowlayer];
    [targetLayer addSublayer:shadowlayer];
    [self addCornerRadiusToLayer:viewLayer];
    
}

- (void)addShadowToLayer:(CALayer *)viewLayer
{
    viewLayer.backgroundColor =[UIColor whiteColor].CGColor;
    viewLayer.opacity = 1.0;
    viewLayer.shadowOffset = CGSizeMake(5, 5);
    viewLayer.shadowRadius =kRoundSize/2;
    viewLayer.shadowColor =[UIColor blackColor].CGColor;
    viewLayer.shadowOpacity =1.0;
    //viewLayer.borderColor =[UIColor whiteColor].CGColor;
    viewLayer.borderWidth =1;
    viewLayer.cornerRadius =kRoundSize;
    
}

- (void)addCornerRadiusToLayer:(CALayer *)viewLayer
{
    
    [viewLayer setCornerRadius:kRoundSize];//设置那个圆角的有多圆
    [viewLayer setBorderWidth:3];//设置边框的宽度，当然可以不要
    [viewLayer setMasksToBounds:YES];//设为NO去试试
    [viewLayer setBorderColor:[UIColor whiteColor].CGColor];
}

- (IBAction)photoLibBtnClicked:(id)sender
{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"照片库",@"相机", nil];
    
    [sheet showInView:[[UIApplication sharedApplication] keyWindow]];
    [sheet release];

}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"%d",buttonIndex);
    UIViewController *vc = nil;
    switch (buttonIndex) {
        case 0:
        {
            UIImagePickerController *imagePicker = [[[UIImagePickerController alloc] init] autorelease];
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePicker.delegate = self;
            [imagePicker setAllowsEditing:YES];
            vc = imagePicker;
            
            break;
        }
        case 1:
        {
            ZBarReaderViewController *reader = [ZBarReaderViewController new];
            reader.readerDelegate = self;
            
            if([ZBarReaderController isSourceTypeAvailable:
                UIImagePickerControllerSourceTypeCamera])
                reader.sourceType = UIImagePickerControllerSourceTypeCamera;
            [reader.scanner setSymbology: ZBAR_I25
                                  config: ZBAR_CFG_ENABLE
                                      to: 0];
            reader.supportedOrientationsMask = ZBarOrientationMaskAll;
            vc = reader;
    
            break;
        }
            
        default:
            break;
    }
    
    if (vc)
    {
        [self presentViewController:vc animated:YES completion:nil];
        [vc release];
    }
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        id<NSFastEnumeration> results =
        [info objectForKey: ZBarReaderControllerResults];
        ZBarSymbol *symbol = nil;
        for(symbol in results)
        {
            NSString *resultStr = symbol.data;
            NSArray *strArray = [resultStr componentsSeparatedByString:@"-"];
            NSString *miniCode = nil;
            NSString *padCode = nil;
            if (strArray.count>0)
            {
                padCode = [strArray objectAtIndex:0];
            }
            
            if (strArray.count>1) {
                miniCode = [strArray objectAtIndex:1];
            }
            
            [self decodedWithMiniCode:miniCode padCode:padCode];
            break;
        }
        
    }else
    {
        UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        self.reader = [[SXQRCodeReader alloc] initWithImage:originalImage delegate:self];
        [self.reader release];
    
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{

    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)decodedWithMiniCode:(NSString *)miniCode padCode:(NSString *)padCode
{
    [self.miniCodeField setText:miniCode];
    [self.padCodeField setText:padCode];
    [self showCodeButtonClicked:nil];
}
- (void)decodeFaild
{
     UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:nil message:@"" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil] autorelease];
    [alert show];
}

@end
